package com.erp.activity

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.text.Html
import android.util.DisplayMetrics
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import com.android.dingtalk.share.ddsharemodule.DDShareApiFactory
import com.android.dingtalk.share.ddsharemodule.IDDShareApi
import com.android.dingtalk.share.ddsharemodule.message.SendAuth
import com.erp.Interface.OnUserDataInterface
import com.erp.Myapp
import com.erp.R
import com.erp.contacts.Contacts
import com.erp.mclass.UpdataInfo
import com.erp.module.miMa.MiMaActivity
import com.erp.module.pieceworkGrouping.PieceworkGroupingM
import com.erp.module.xieyi.PrivacyDialog
import com.erp.module.xieyi.XieyiActivity
import com.erp.util.Httputil
import com.erp.util.JsonUtil
import com.erp.util.Myutil
import com.erp.util.Myutil.httperrordiaog
import com.erp.util.Sputil
import kotlinx.android.synthetic.main.activity_login.*
import org.json.JSONObject
import org.xutils.http.cookie.DbCookieStore


/**
 * Created by Administrator on 2016/11/02/028.
 * 作者：刘洋
 */
class LoginActivity : BaseActivity(), TextView.OnEditorActionListener {


    private var name: String =""
    private var password: String =""
    private var child_name: String =""//输入的账号和密码子账号
    private var islogin = false//登录状态，true为已登录
    private var isxieyi = false;
    lateinit var updatedialog: AlertDialog
    private var country: List<String> = arrayListOf()


    private var lishiname: String = ""

    private var token = ""
    private var username = ""
    private var uid = ""
    private var mail = ""
    private var dingdingtype = 1;
    override fun getLayoutId(): Int {
        activityname = a
        return R.layout.activity_login
    }

    override fun initCreate() {
        Log.d("TAAAG","+++++++++++++++++++++++")
        initView()//初始化控件
        initclick()//控件监听
        EtMainNumble.hint = "用户名/手机号"
        UpdataInfo(this, false, Sputil.sp("")).show()
        setupCountry()
        val filter = IntentFilter()
        filter.addAction(Contacts.BORADCAST_ACTION_DINGDING)//为BroadcastReceiver指定一个action，即要监听的消息名字
        registerReceiver(mBoradcastReceiver, filter) //动态注册监听  静态的话 在AndroidManifest.xml中定义
        EtMainNumble.setOnEditorActionListener(this)
        EtPassword.setOnEditorActionListener(this)
        EtSonNumble.setOnEditorActionListener(this)
        var dialog = PrivacyDialog(this)
        isxieyi = sp.getBoolean("isxieyi", islogin)
        if(!isxieyi){
            dialog.showPrivacy(this,dialog,editor);
        }

    }

    /**
     * 广播接受着，用于在退出时关闭activity
     */
    private val mBoradcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == Contacts.BORADCAST_ACTION_DINGDING) {//关闭app的广播
                var auth_code = intent.getStringExtra("auth_code")
                updatedialog = Myutil.showupdatedialog(this@LoginActivity, "正在登录", true)
                if(dingdingtype == 1){
                    Httputil.setDingDIng(this@LoginActivity,auth_code,object : OnUserDataInterface{
                        override fun onUserData(data: String) {
                            jsondata(data)
                        }

                        override fun onNot(throwable: String?) {
                            updatedialog.dismiss()
                        }

                    })
                }else if(dingdingtype == 2){
                    Httputil.setGongChengDingDIng(this@LoginActivity,auth_code,object : OnUserDataInterface{
                        override fun onUserData(data: String) {
                            jsondata(data)
                        }

                        override fun onNot(throwable: String?) {
                            updatedialog.dismiss()
                        }

                    })
                }

            }
        }
    }

    private fun setupCountry() {
        country= Sputil.sp("name").getString("lishiname", "")?.split(",") ?: listOf("");
        val av = ArrayAdapter(this,
                android.R.layout.simple_dropdown_item_1line, country)
        EtMainNumble.setAdapter(av)
        EtMainNumble.threshold = 1
    }

    //控件监听
    private fun initclick() {
        TvDingDing.setOnClickListener {
            dingdingtype = 1;
            sendAuth()
        }
        TvDingDingGongcheng.setOnClickListener {
            dingdingtype = 2;
            gongchengsendAuth()
        }
        CbSon.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                LlSon.visibility = View.VISIBLE
                EtMainNumble.hint = "主账号"
            } else {
                LlSon.visibility = View.GONE
                EtMainNumble.hint = "用户名/手机号"
                EtSonNumble.setText("")
            }
        }

        BtSingin.setOnClickListener {
            if (EtMainNumble.text.toString() != "" && EtPassword.text.toString() != "") {
                updatedialog = Myutil.showupdatedialog(this@LoginActivity, "正在登录", true)
                httplogin()
            } else {
                Myutil.MyTost("请输入用户名和密码")
            }
        }
        TvZhaoHui!!.setOnClickListener {
            val intent = Intent(this@LoginActivity, MiMaActivity::class.java)
            startActivity(intent)
        }
    }

    lateinit var iddShareApi: IDDShareApi
    private fun sendAuth() {
        iddShareApi = DDShareApiFactory.createDDShareApi(this, Contacts.APP_ID, true)
        val req = SendAuth.Req()
        req.scope = SendAuth.Req.SNS_LOGIN
        req.state = "test"
        if (req.supportVersion > iddShareApi.ddSupportAPI) {
            httperrordiaog(this, "未安装钉钉或者钉钉版本过低，不支持登录授权")
            return
        }
        iddShareApi.sendReq(req)
    }

    private  fun gongchengsendAuth(){
        iddShareApi = DDShareApiFactory.createDDShareApi(this, Contacts.GongCheng_APP_ID, true)
        val req = SendAuth.Req()
        req.scope = SendAuth.Req.SNS_LOGIN
        req.state = "test"
        if (req.supportVersion > iddShareApi.ddSupportAPI) {
            httperrordiaog(this, "未安装钉钉或者钉钉版本过低，不支持登录授权")
            return
        }
        iddShareApi.sendReq(req)
    }

    //初始化控件
    private fun initView() {
        islogin = sp.getBoolean("islogin", islogin)
        metric()//获取屏幕属性并存储
    }

    //存储屏幕属性
    private fun metric() {
        val metric = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(metric)
        val width = metric.widthPixels     // 屏幕宽度（像素）
        val height = metric.heightPixels   // 屏幕高度（像素）
        val density = metric.density      // 屏幕密度（0.75 / 1.0 / 1.5）
        val densityDpi = metric.densityDpi  // 屏幕密度DPI（120 / 160 / 240）
        editor.putInt("width", width)
        editor.putInt("height", height)
        editor.commit()
    }

    //登录网络访问
    private fun httplogin() {
//        var P = PieceworkGroupingM()
//        P.getPieceworkcoll(this@LoginActivity,1,2,object : OnUserDataInterface{
//            override fun onUserData(data: String?) {
//                Log.d("TAAG",data)
//            }
//
//            override fun onNot(throwable: String?) {
//            }
//
//        })
        name = EtMainNumble.text.toString().trim()
        password = EtPassword.text.toString().trim()
        child_name = EtSonNumble.text.toString().trim ()
        Httputil.setLogin(this, name, password, child_name, object : OnUserDataInterface {
            override fun onUserData(s: String) {
                jsondata(s)
            }

            override fun onNot(s: String) {
                updatedialog.dismiss()
                EtPassword.setText("")
            }
        })
    }

    fun jsondata(s : String){
        try {
            val jo = JSONObject(s)
            token = JsonUtil.getvolue(jo, "token")
            val session_name = JsonUtil.getvolue(jo, "session_name")
            val jouser = JsonUtil.getjovolue(jo, "user")
            if (jouser != null) {
                username = jouser.getString("name")
                mail = jouser.getString("mail")
                uid = jouser.getString("uid")
            }
            val instance = DbCookieStore.INSTANCE
            val cookies = instance.cookies
//            var cookiedata = ""
            for (i in cookies.indices) {
                val cookie = cookies[i]
//                cookiedata = cookiedata+cookie.name+"-"+cookie.value+"; "
                if (cookie.name == session_name) {
                    editor.putString("cookie", session_name + "=" + cookie.value)
                } else if(cookie.name == "knoya_wms_session") {
                    editor.putString("knoya_wms_session", cookie.name + "=" + cookie.value)
//                    editor.putString("cookies", cookie.name + "=" + cookie.value)
                }
            }
//            editor.putString("cookie", cookiedata)
            instance.removeAll()
            editor.putString("uid", uid)
            editor.putString("mail", mail)
            editor.putString("name", username)
            editor.putString("token", token)
            editor.putString("user", jouser!!.toString())
            editor.putBoolean("islogin", true)
            editor.commit()
        } catch (e: Exception) {
            Myutil.Mylog("TAAAAG", e.toString())
            e.printStackTrace()
        }

        Httputil.setdeviceID(this@LoginActivity, Myapp.getpushService().deviceId, object : OnUserDataInterface {
            override fun onUserData(data: String) {
                Myutil.Mylog("setdeviceID", data)
            }

            override fun onNot(throwable: String) {
                Myutil.Mylog("setdeviceID", "error="+throwable)
            }
        })
        val intent = Intent(this@LoginActivity, NewMainKActivity::class.java)
        startActivity(intent)
        if (!isyou(name)) {
            if (lishiname == null) {
                lishiname = ""
            }
            Sputil.editor("name").putString("lishiname", lishiname + "," + name).commit()
        }
        finish()
    }

    private fun isyou(name: String?): Boolean {
        for (i in country.indices) {
            if (country[i] == name) {
                return true
            }
        }
        return false
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == 4) {
            finish()
        }
        return true
    }

    companion object {
        val TAG = "LoginActivity"
        private val a = "LoginActivity"
    }

    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        return true
    }


}

